from django.http import JsonResponse
from django.shortcuts import render
from main.models import Category, Book
from .models import MyBookshelf
from django.contrib.auth.decorators import login_required


# Create your views here.

@login_required
def collect(request):
    cs = Category.objects.all()
    mb = MyBookshelf.objects.all()
    return render(request, 'operate/collect.html', context={"cs": cs, "mb": mb})


def add_book(request):
    if request.method == "POST":
        book_id = request.POST.get("book_id")
        book = Book.objects.get(id=book_id)
        c = MyBookshelf.objects.filter(user=request.user, book=book).first()
        if c:
            c.delete()
            return JsonResponse({
                "code": 0,
                "msg": "取消收藏成功",
                "data": {
                    "state": False
                }
            })
        else:
            temp = MyBookshelf()
            temp.user = request.user
            temp.book = book
            temp.save()
            return JsonResponse({
                "code": 0,
                "msg": "收藏成功",
                "data": {
                    "state": True
                }
            })
    else:
        return JsonResponse({
            "code": -1,
            "msg": "方法不允许"
        })
